package binarytree;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/22 23:31
 * https://leetcode-cn.com/problems/validate-binary-search-tree/
 */
public class IsValidBST {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 迭代 中序遍历下，输出的二叉搜索树节点的数值是有序序列。
     * @param root
     * @return
     */
    public static boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode pop = stack.pop();
            if (pre != null && pop.val <= pre.val) {
                return false;
            } else {
                pre = pop;
            }
            root = pop.right;
        }
        return true;
    }


    static TreeNode pre;
    /**
     * 递归法
     * @param root
     * @return
     */
    public static boolean isValidBST1(TreeNode root) {
        pre = null;
        return traversal(root);
    }

    public static boolean traversal(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean left = traversal(root.left);
        if (pre != null && root.val <= pre.val) {
            return false;
        }else{
            pre = root;
        }
        boolean right = traversal(root.right);
        return left && right;
    }


    public static void main(String[] args) {
        TreeNode t = new TreeNode(1);
        t.left = new TreeNode(1);
        //t.right = new TreeNode(5);
        boolean validBST1 = isValidBST1(t);
        System.out.println(validBST1);
    }
}
